{% extends "base.html" %}

{% block title %}数据监控 - 头条自动发文系统{% endblock %}
{% block page_title %}数据监控{% endblock %}

{% block content %}
<div class="row">
    <!-- 统计概览 -->
    <div class="col-12 mb-4">
        <div class="row">
            <div class="col-md-2">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-eye fa-2x text-primary mb-2"></i>
                        <h5 class="card-title">总阅读量</h5>
                        <p class="card-text">
                            <span class="h3" id="total-views">{{ articles|sum(attribute='views') or 0 }}</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-chart-bar fa-2x text-warning mb-2"></i>
                        <h5 class="card-title">总展现量</h5>
                        <p class="card-text">
                            <span class="h3" id="total-impressions">{{ articles|sum(attribute='impressions') or 0 }}</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-heart fa-2x text-danger mb-2"></i>
                        <h5 class="card-title">总点赞数</h5>
                        <p class="card-text">
                            <span class="h3" id="total-likes">{{ articles|sum(attribute='likes') or 0 }}</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-comment fa-2x text-success mb-2"></i>
                        <h5 class="card-title">总评论数</h5>
                        <p class="card-text">
                            <span class="h3" id="total-comments">{{ articles|sum(attribute='comments') or 0 }}</span>
                        </p>
                    </div>
                </div>
            </div>
            <div class="col-md-2">
                <div class="card text-center">
                    <div class="card-body">
                        <i class="fas fa-file-alt fa-2x text-info mb-2"></i>
                        <h5 class="card-title">发布文章</h5>
                        <p class="card-text">
                            <span class="h3">{{ articles|length }}</span>
                        </p>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 文章列表 -->
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-list text-primary"></i>
                    已发布文章
                </h5>
                <div>
                    <button id="refresh-all" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-sync-alt"></i>
                        刷新全部
                    </button>
                </div>
            </div>
            <div class="card-body">
                {% if articles %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>文章标题</th>
                                <th>发布时间</th>
                                <th>展现量</th>
                                <th>阅读量</th>
                                <th>点赞数</th>
                                <th>评论数</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for article in articles %}
                            <tr data-article-index="{{ loop.index0 }}">
                                <td>
                                    <div class="fw-bold">{{ article.title }}</div>
                                    <small class="text-muted">来源：头条官网</small>
                                </td>
                                <td>
                                    {% if article.published_at %}
                                    <small>{{ article.published_at[:16] }}</small>
                                    {% else %}
                                    <small class="text-muted">-</small>
                                    {% endif %}
                                </td>
                                <td>
                                    <span class="impressions-count">{{ article.impressions or 0 }}</span>
                                    <i class="fas fa-chart-bar text-warning ms-1"></i>
                                </td>
                                <td>
                                    <span class="views-count">{{ article.views or 0 }}</span>
                                    <i class="fas fa-eye text-primary ms-1"></i>
                                </td>
                                <td>
                                    <span class="likes-count">{{ article.likes or 0 }}</span>
                                    <i class="fas fa-heart text-danger ms-1"></i>
                                </td>
                                <td>
                                    <span class="comments-count">{{ article.comments or 0 }}</span>
                                    <i class="fas fa-comment text-success ms-1"></i>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-info refresh-stats" 
                                            data-article-index="{{ loop.index0 }}">
                                        <span class="loading spinner-border spinner-border-sm me-1" role="status"></span>
                                        <i class="fas fa-sync-alt"></i>
                                        刷新
                                    </button>
                                    <button class="btn btn-sm btn-outline-primary view-details" 
                                            data-article-index="{{ loop.index0 }}" 
                                            data-title="{{ article.title }}">
                                        <i class="fas fa-chart-bar"></i>
                                        详情
                                    </button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
                {% else %}
                <div class="text-center py-5">
                    <i class="fas fa-chart-line fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">暂无已发布文章</h5>
                    <p class="text-muted">发布文章后，您可以在这里监控数据表现</p>
                    <div class="mt-3">
                        <a href="/generate" class="btn btn-primary me-2">
                            <i class="fas fa-magic"></i>
                            生成文章
                        </a>
                        <a href="/publish" class="btn btn-outline-primary">
                            <i class="fas fa-paper-plane"></i>
                            发布文章
                        </a>
                    </div>
                </div>
                {% endif %}
            </div>
        </div>
    </div>
</div>

<!-- 文章详情模态框 -->
<div class="modal fade" id="detailsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-chart-bar text-info"></i>
                    文章数据详情
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <h6 id="detail-title" class="mb-3"></h6>
                
                <div class="row">
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-chart-bar fa-2x text-warning mb-2"></i>
                                <h5>展现量</h5>
                                <p class="h4" id="detail-impressions">0</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-eye fa-2x text-primary mb-2"></i>
                                <h5>阅读量</h5>
                                <p class="h4" id="detail-views">0</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-heart fa-2x text-danger mb-2"></i>
                                <h5>点赞数</h5>
                                <p class="h4" id="detail-likes">0</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card text-center">
                            <div class="card-body">
                                <i class="fas fa-comment fa-2x text-success mb-2"></i>
                                <h5>评论数</h5>
                                <p class="h4" id="detail-comments">0</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="mt-4">
                    <h6>数据趋势</h6>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i>
                        数据趋势图功能开发中，敬请期待
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" id="refresh-detail" class="btn btn-primary">
                    <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                    <i class="fas fa-sync-alt"></i>
                    刷新数据
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    let currentArticleIndex = null;
    
    // 检查连接状态后再执行操作
    function checkConnectionBeforeAction(callback) {
        if (!isConnected || !isLoggedIn) {
            showAlert('请先确保浏览器连接正常且已登录', 'warning');
            return false;
        }
        if (callback) callback();
        return true;
    }
    
    // 刷新单个文章统计
    $('.refresh-stats').click(function() {
        if (!checkConnectionBeforeAction()) return;
        const articleIndex = $(this).data('article-index');
        const $row = $(this).closest('tr');
        
        showLoading(this, true);
        
        $.post(`/api/refresh-stats/${articleIndex}`)
            .done(function(response) {
                if (response.success) {
                    // 更新表格中的数据
                    $row.find('.impressions-count').text(response.stats.impressions);
                    $row.find('.views-count').text(response.stats.views);
                    $row.find('.likes-count').text(response.stats.likes);
                    $row.find('.comments-count').text(response.stats.comments);
                    
                    // 更新总计
                    updateTotals();
                    
                    showAlert('数据已刷新', 'success');
                } else {
                    showAlert(response.message, 'warning');
                }
            })
            .fail(function() {
                showAlert('刷新失败，请重试', 'danger');
            })
            .always(function() {
                showLoading($('.refresh-stats[data-article-index="' + articleIndex + '"]'), false);
            });
    });
    
    // 刷新全部统计
    $('#refresh-all').click(function() {
        if (!checkConnectionBeforeAction()) return;
        
        showLoading(this, true);
        
        $.post('/api/refresh-stats')
            .done(function(response) {
                if (response.success) {
                    // 重新加载页面以显示最新数据
                    location.reload();
                } else {
                    showAlert(response.message, 'warning');
                }
            })
            .fail(function() {
                showAlert('刷新失败，请重试', 'danger');
            })
            .always(function() {
                showLoading($('#refresh-all'), false);
            });
    });
    
    // 查看详情
    $('.view-details').click(function() {
        const articleIndex = $(this).data('article-index');
        const title = $(this).data('title');
        const $row = $(this).closest('tr');
        
        currentArticleIndex = articleIndex;
        
        // 设置模态框内容
        $('#detail-title').text(title);
        $('#detail-impressions').text($row.find('.impressions-count').text());
        $('#detail-views').text($row.find('.views-count').text());
        $('#detail-likes').text($row.find('.likes-count').text());
        $('#detail-comments').text($row.find('.comments-count').text());
        
        $('#detailsModal').modal('show');
    });
    
    // 刷新详情数据
    $('#refresh-detail').click(function() {
        if (currentArticleIndex === null) return;
        if (!checkConnectionBeforeAction()) return;
        
        showLoading(this, true);
        
        $.post(`/api/refresh-stats/${currentArticleIndex}`)
            .done(function(response) {
                if (response.success) {
                    $('#detail-impressions').text(response.stats.impressions);
                    $('#detail-views').text(response.stats.views);
                    $('#detail-likes').text(response.stats.likes);
                    $('#detail-comments').text(response.stats.comments);
                    
                    // 同时更新表格中的数据
                    const $row = $(`tr[data-article-index="${currentArticleIndex}"]`);
                    $row.find('.impressions-count').text(response.stats.impressions);
                    $row.find('.views-count').text(response.stats.views);
                    $row.find('.likes-count').text(response.stats.likes);
                    $row.find('.comments-count').text(response.stats.comments);
                    
                    updateTotals();
                    showAlert('数据已刷新', 'success');
                } else {
                    showAlert(response.message, 'warning');
                }
            })
            .fail(function() {
                showAlert('刷新失败，请重试', 'danger');
            })
            .always(function() {
                showLoading($('#refresh-detail'), false);
            });
    });
    
    // 更新总计数据
    function updateTotals() {
        let totalViews = 0;
        let totalImpressions = 0;
        let totalLikes = 0;
        let totalComments = 0;
        
        $('.views-count').each(function() {
            totalViews += parseInt($(this).text()) || 0;
        });
        
        $('.impressions-count').each(function() {
            totalImpressions += parseInt($(this).text()) || 0;
        });
        
        $('.likes-count').each(function() {
            totalLikes += parseInt($(this).text()) || 0;
        });
        
        $('.comments-count').each(function() {
            totalComments += parseInt($(this).text()) || 0;
        });
        
        $('#total-views').text(totalViews);
        $('#total-impressions').text(totalImpressions);
        $('#total-likes').text(totalLikes);
        $('#total-comments').text(totalComments);
    }
    
    // 定时刷新（可选）
    let autoRefreshInterval = null;
    
    function startAutoRefresh() {
        if (autoRefreshInterval) return;
        
        autoRefreshInterval = setInterval(function() {
            if ($('.refresh-stats').length > 0) {
                $('#refresh-all').click();
            }
        }, 300000); // 每5分钟刷新一次
    }
    
    function stopAutoRefresh() {
        if (autoRefreshInterval) {
            clearInterval(autoRefreshInterval);
            autoRefreshInterval = null;
        }
    }
    
    // 页面可见时开启自动刷新
    document.addEventListener('visibilitychange', function() {
        if (document.hidden) {
            stopAutoRefresh();
        } else {
            startAutoRefresh();
        }
    });
    
    // 初始化自动刷新
    startAutoRefresh();
});
</script>
{% endblock %}
